package com.qst.order.config;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;


@Configuration
public class SecurityConfig {

    @Autowired
    private JwtFilter jwtFilter;
    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler; // 注入未认证处理器


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 1. 授权配置
                .authorizeHttpRequests(auth ->auth
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允许所有OPTIONS请求
                        .requestMatchers("/api/user/register","/api/user/login").permitAll()
                        .anyRequest().authenticated()
                )
//                 2. 未认证处理（添加异常处理配置）
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(unauthorizedHandler)
                        .accessDeniedHandler((request, response, accessDeniedException) -> {
                            // 处理403（无权限）
                            response.sendError(HttpServletResponse.SC_FORBIDDEN, "无权限访问");
                        })
                )
                // 3. 禁用CSRF
                .csrf(AbstractHttpConfigurer::disable)
                // 4. 无状态会话
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                // 5. 禁用默认登录方式
                .formLogin(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable);

        // 6. 添加JWT过滤器
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // SecurityConfig.java 中添加 CorsConfigurationSource Bean
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        // 1. 允许的前端域名（生产环境替换为实际域名，如 "http://localhost:5173"）
        config.setAllowedOrigins(Collections.singletonList("http://localhost:5173"));
        // 2. 允许的 HTTP 方法（必须包含 OPTIONS，因为预检是 OPTIONS 请求）
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 3. 允许的请求头（必须包含前端发送的所有自定义头，如 Authorization、Content-Type）
        config.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
        // 4. 是否允许携带凭证（如 Cookie，若前端无此需求可设为 false）
        config.setAllowCredentials(false);
        // 5. 预检结果缓存时间（减少 OPTIONS 请求次数）
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有路径生效
        return source;
    }



    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}